/**
 * Copyright 2013 wasu.com
 *
 *
 * Create on 2014-7-31 下午9:47:34
 */
package xj.toolkit.netty.handler.codec.http.transformer;

import java.util.Map;

import org.apache.commons.collections4.Transformer;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import xj.toolkit.ebus.EventBus;
import xj.toolkit.netty.handler.codec.http.transformer.HttpRequestTransformer;

import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;

import io.netty.handler.codec.http.FullHttpRequest;

/**
 * clazz:event,class:event.
 * 
 * @author <a href="mailto:caoxiaojian@wasu.com>xiaojian.cao</a>
 * 
 */
public class FireMultiEventTransformer implements HttpRequestTransformer {

	private static final Logger logger = LoggerFactory
			.getLogger(FireMultiEventTransformer.class);

	private EventBus eventBus;
	private Map<String, String> maps = Maps.newHashMap();

	/**
	 * @param event
	 *            the event to set
	 */
	public void setRequestEventMap(String events) {
		Preconditions.checkArgument(events != null);
		String[] requestEventMaps = StringUtils.split(events, ",");
		if (requestEventMaps == null || requestEventMaps.length == 0) {
			throw new IllegalArgumentException("Invalid argument[" + events
					+ "], must be[clazz:event,class:event,...].");
		}
		for (String str : requestEventMaps) {
			String[] requestEventMap = StringUtils.split(str, ":");
			maps.put(requestEventMap[0], requestEventMap[1]);
		}
	}

	/**
	 * @return the eventBus
	 */
	public EventBus getEventBus() {
		return eventBus;
	}

	/**
	 * @param eventBus
	 *            the eventBus to set
	 */
	public void setEventBus(EventBus eventBus) {
		this.eventBus = eventBus;
	}

	/**
	 * @return the impl
	 */
	public Transformer getImpl() {
		return impl;
	}

	/**
	 * @param impl
	 *            the impl to set
	 */
	public void setImpl(Transformer impl) {
		this.impl = impl;
	}

	private Transformer impl;

	@Override
	public Object transform(FullHttpRequest from) {
		Object bean = impl.transform(from);

		if (null != bean) {
			String beanClassName = bean.getClass().getName();
			String event = maps.get(beanClassName);
			if (event == null) {
				throw new RuntimeException("Cannot get event by class["
						+ beanClassName + "].");
			}
			if (!eventBus.fireEvent(event, bean)) {
				logger.warn("Event bus is busy. event[{}], bean[{}].", event,
						bean);
				throw new HttpTransformException(503, "SERVER_BUSY");
			}
		}
		return bean;
	}
}
